package com.jdrx.ocp.api;

import com.jdrx.ocp.beans.constans.EventActionEnum;
import com.jdrx.ocp.beans.constans.EventEnum;
import com.jdrx.ocp.beans.dto.dept.QueryByIdsDTO;
import com.jdrx.ocp.beans.dto.login.LoginDTO;
import com.jdrx.ocp.beans.dto.role.QueryRoleNoPageDTO;
import com.jdrx.ocp.beans.dto.system.FindDeptLeaderByUserIdsDTO;
import com.jdrx.ocp.beans.dto.user.CreateUserDTO;
import com.jdrx.ocp.beans.dto.user.LoginCheckDTO;
import com.jdrx.ocp.beans.dto.user.QueryOpenUserDTO;
import com.jdrx.ocp.beans.event.NoticesEvent;
import com.jdrx.ocp.beans.vo.LoginUserVO;
import com.jdrx.ocp.service.*;
import com.jdrx.ocp.utils.Constants;
import com.jdrx.ocp.utils.ValidateUtils;
import com.jdrx.platform.common.support.gateway.GwConstants;
import com.jdrx.platform.commons.rest.beans.dto.IdDTO;
import com.jdrx.platform.commons.rest.beans.dto.IdsDTO;
import com.jdrx.platform.commons.rest.beans.vo.ResponseVO;
import com.jdrx.platform.commons.rest.beans.vo.ResposeVO;
import com.jdrx.platform.commons.rest.exception.BizException;
import com.jdrx.platform.commons.rest.factory.ResponseFactory;
import com.jdrx.platform.commons.rest.factory.ResponseFactory2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.Optional;

import static com.jdrx.platform.common.support.gateway.GwConstants.TRANSPARENT_USERID_FEILD;

@RestController
@RequestMapping(value = "/system/0/admin")
@Api(value = "系统公用")
@Validated
public class SystemApi {
    @Autowired
    private AdminService adminService;
    @Autowired
    private NoticeEventService noticeEventService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private OpenService openService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private ValidateUtils validateUtils;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private UserService userService;

    @ApiOperation("登录")
    @PostMapping("login")
    public ResponseVO<LoginUserVO> login(@RequestBody @Valid LoginDTO dto,
                                         @RequestHeader(GwConstants.TRANSPARENT_TENANT_ID) Long tenantId) throws Exception {
        return ResponseFactory2.ok(adminService.platformLogin(dto, tenantId));
    }

    @ApiOperation(value = "退出登陆", notes = "退出登陆")
    @RequestMapping(value = "logout", method = RequestMethod.POST)
    //@BizLogger(description = "用户退出登录",serviceId = SysConstant.APPLICATION_NAME)
    public ResposeVO logout(@RequestBody(required = false) IdDTO<Long> idDTO,
                            @RequestHeader(value = TRANSPARENT_USERID_FEILD, required = false) Long userId,
                            HttpServletRequest httpServletRequest,
                            @RequestHeader(value = Constants.TENANT_ID, required = false) Long tid) {
        userId = Optional.ofNullable(userId).orElse(idDTO.getId());
        //noticeEventService.publishEvent(new NoticesEvent(this,EventEnum.LOGOUT,EventActionEnum.LOGOUT,String.valueOf(userId)));
        adminService.logout(userId, httpServletRequest, tid);
        return ResponseFactory.ok(true);
    }

    @ApiOperation(value = "退出登陆", notes = "退出登陆")
    @RequestMapping(value = "/dubbo/logout", method = RequestMethod.POST)
    //@BizLogger(description = "用户退出登录",serviceId = SysConstant.APPLICATION_NAME)
    public ResposeVO dblogout(@RequestHeader(value = TRANSPARENT_USERID_FEILD) Long userId,
                              @RequestHeader(value = Constants.TENANT_ID, required = false, defaultValue = "") String tid) {
        noticeEventService.publishEvent(new NoticesEvent(this, EventEnum.LOGOUT, EventActionEnum.LOGOUT, String.valueOf(userId)));
        adminService.logout(userId, tid);
        return ResponseFactory.ok(true);
    }

    @ApiOperation(value = "踢出登录用户", notes = "踢出登录用户")
    @RequestMapping(value = "kickOut", method = RequestMethod.POST)
    //@BizLogger(description = "踢出登录用户",serviceId = SysConstant.APPLICATION_NAME)
    public ResposeVO kickOut(@RequestBody IdDTO<Long> idDTO,
                             HttpServletRequest httpServletRequest,
                             @RequestHeader(value = Constants.TENANT_ID, required = false) Long tid) {
        noticeEventService.publishEvent(new NoticesEvent(this, EventEnum.LOGOUT, EventActionEnum.LOGOUT, String.valueOf(idDTO.getId())));
        adminService.logout(idDTO.getId(), httpServletRequest, tid);
        return ResponseFactory.ok(true);
    }

    @ApiOperation(value = "获取验证码图片", notes = "获取验证码图片")
    @RequestMapping(value = "generateValidateCode", method = RequestMethod.GET)
    public void generateValidateCode(HttpServletRequest httpServletRequest,
                                     HttpServletResponse httpServletResponse,
                                     @ApiParam(required = true, name = "uniqueId", value = "uniqueId浏览器标识信息")
                                     @RequestParam(value = "uniqueId") String uniqueId) throws IOException {
        validateUtils.createImage(httpServletRequest, httpServletResponse, uniqueId);
    }

    @ApiOperation(value = "是否验证码登录", notes = "是否验证码登录")
    @RequestMapping(value = "isValidateCodeLogin", method = RequestMethod.POST)
    public ResposeVO isValidateCodeLogin(@RequestBody @Valid IdDTO<String> idDTO) throws IOException {
        return ResponseFactory.ok(validateUtils.isValidateCodeLogin(idDTO.getId(), false, false));
    }

    @ApiOperation(value = "获取浏览器唯一标识", notes = "获取浏览器唯一标识")
    @RequestMapping(value = "generateBrowserUniqueId", method = RequestMethod.POST)
    public ResposeVO generateBrowserUniqueId(HttpServletRequest httpServletRequest,
                                             HttpServletResponse httpServletResponse,
                                             @ApiParam(required = true, name = "idsDto浏览器信息", value = "idsDto浏览器信息") @RequestBody @Valid IdsDTO idsDTO) throws IOException, BizException {
        return adminService.generateBrowserUniqueId(idsDTO.getIds());
    }

    @RequestMapping(value = "getRoles", method = RequestMethod.POST)
    @ApiOperation(value = "获取角色信息", notes = "获取角色信息")
    public ResposeVO getRoles(@ApiParam(required = true) @RequestBody @Valid QueryRoleNoPageDTO queryRoleDTO) throws BizException {
        return ResponseFactory.ok(roleService.queryRoles(queryRoleDTO));
    }

    @RequestMapping(value = "getUsers", method = RequestMethod.POST)
    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    public ResposeVO getUsers(@RequestBody @Valid QueryOpenUserDTO queryOpenUserDTO) throws BizException {
        return ResponseFactory.ok(openService.getUserAll(queryOpenUserDTO));
    }

    @RequestMapping(value = "getDeptAllParents", method = RequestMethod.POST)
    @ApiOperation(value = "根据ID集获取本身以及其父级部门信息", notes = "根据ID集获取本身以及其父级部门信息")
    public ResposeVO getDeptAllParents(@ApiParam(required = true) @RequestBody @Valid QueryByIdsDTO idsDTO) throws BizException {
        return ResponseFactory.ok(deptService.getDeptAllParents(idsDTO.getIds()));
    }

    @RequestMapping(value = "getDeptParents", method = RequestMethod.POST)
    @ApiOperation(value = "根据ID获取本身以及其父级部门信息", notes = "根据ID获取本身以及其父级部门信息")
    public ResposeVO getDeptParents(@ApiParam(required = true) @RequestBody @Valid IdDTO<Long> idDTO) throws BizException {
        return ResponseFactory.ok(deptService.getDeptParents(idDTO.getId()));
    }

    @RequestMapping(value = "getServerTime", method = RequestMethod.POST)
    @ApiOperation(value = "获取服务器时间", notes = "获取服务器时间")
    public ResposeVO getServerTime() {
        return ResponseFactory.ok(new Date());
    }

    @ApiOperation(value = "获取平台内部服务信息", notes = "获取平台内部服务信息")
    @RequestMapping(value = "queryPlatformByInterior", method = RequestMethod.POST)
    public ResposeVO queryPlatformByInterior() {
        return ResponseFactory.ok(platformService.queryPlatformByInterior());
    }


    @RequestMapping(value = "getDeptLeaderByUserIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据用户ids获取部门负责人", notes = "根据用户ids获取部门负责人")
    public ResposeVO findDeptLeaderByUserIds(@RequestBody @Valid FindDeptLeaderByUserIdsDTO findDeptLeaderByUserIdsDTO) throws BizException {
        return ResponseFactory.ok(deptService.findDeptLeaderByUserIds(findDeptLeaderByUserIdsDTO));
    }

    /*@ApiOperation(value = "微信端登录", notes = "微信端登录")
    @RequestMapping(value = "loginWeChat", method = RequestMethod.POST)
    @BizLogger(description = "微信端登录",serviceId = SysConstant.APPLICATION_NAME)
    public ResposeVO loginWeChat(@ApiParam(required = true ) @RequestBody @Valid LoginWeChatDTO dto) throws BizException {
        return ResponseFactory.ok(adminService.loginWeChat(dto));
    }

    @ApiOperation(value = "微信端绑定openID", notes = "微信端绑定openID")
    @RequestMapping(value = "bindingOpenId", method = RequestMethod.POST)
    @BizLogger(description = "微信端绑定openID",serviceId = SysConstant.APPLICATION_NAME)
    public ResposeVO bindingOpenId(@ApiParam(required = true ) @RequestBody @Valid BindingOpenIdDTO dto) throws BizException {
        adminService.bindingOpenId(dto);
        return ResponseFactory.ok(EApiStatus.SUCCESS);
    }*/

    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "queryDeptUserByDeptName", method = RequestMethod.POST)
    @ApiOperation(value = "根据部门名称查询部门用户列表（含子部门用户）", notes = "根据部门名称查询部门用户列表（含子部门用户）")
    public ResposeVO queryDeptUserByDeptName(@ApiParam(required = true) @RequestBody @Valid IdDTO idDTO) throws BizException {
        return ResponseFactory.ok(deptService.queryDeptUserByDeptName(String.valueOf(idDTO.getId())));
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ApiOperation(value = "创建用户数据", notes = "添加一条用户数据")
    public ResposeVO create(@RequestBody @Valid CreateUserDTO createUserDTO,
                            @RequestHeader(TRANSPARENT_USERID_FEILD) Integer uId,
                            @RequestHeader(value = Constants.TENANT_ID, required = false, defaultValue = "") String tid) throws BizException {
        return ResponseFactory.ok(userService.createUser(createUserDTO, uId, tid));
    }

    @ApiOperation(value = "登录账号校验")
    @PostMapping("loginCheck")
    public ResposeVO loginCheck(@RequestBody @Validated LoginCheckDTO dto) throws BizException {
        return ResponseFactory.ok(userService.loginCheck(dto));
    }
}